import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:path_provider/path_provider.dart';

import '../config/public_text.dart';
import '../widget/indicator/toast.dart';

/// FileName file_manager
///
/// @Author lax
/// @Date 2023/12/1
///
/// @Description

class FileManager {
  /// 上传附件文件类型限制
  static List<String>? allowedExtensions = [
    '.jpg',
    '.jpeg',
    '.png',
    '.pdf',
    '.doc',
    '.docx',
    '.xls',
    '.xlsx',
    '.ppt',
    '.pptx',
    '.txt',
    '.mp4',
  ];

  /// 图片类型格式
  static List<String> imageExtensions = [
    '.jpg',
    '.jpeg',
    '.png',
  ];

  /// 判断文件是否存在
  static bool fileIsExist({String? path}) {
    if (path == null) {
      return false;
    }
    File file = File(path);
    return file.existsSync();
  }

  /// 删除文件
  static Future<bool> deleteFile({String? path}) async {
    if (path == null) {
      return false;
    }
    try {
      File file = File(path);
      await file.delete(recursive: true);
    } catch (_) {
      return false;
    }
    return true;
  }

  /// 复制文件
  static void copyFile(
      {required String? sourcePath, required String? destinationPath}) {
    if (sourcePath == null || destinationPath == null) {
      return;
    }
    File sourceFile = File(sourcePath);
    File destinationFile = File(destinationPath);
    sourceFile.copySync(destinationFile.path);
  }

  /// 移动文件
  static void moveFile(
      {required String? sourcePath, required String? destinationPath}) {
    if (sourcePath == null || destinationPath == null) {
      return;
    }
    copyFile(sourcePath: sourcePath, destinationPath: destinationPath);
    deleteFile(path: sourcePath);
  }

  /// 获取沙盒目录
  static Future<String> getHomeDirectoryPath({
    bool temp = false,
    bool external = false,
    String? path, // 以"/"开头
  }) async {
    String newPath;
    if (temp) {
      // 临时目录
      final directory = await getTemporaryDirectory();
      newPath = '${directory.path}${path ?? ''}';
    } else if (external) {
      // 外部存储目录/应用程序支持目录
      final directory = Platform.isAndroid
          ? await getExternalStorageDirectory()
          : await getApplicationSupportDirectory();
      newPath = '${directory?.path}${path ?? ''}';
    } else {
      // 文档目录
      final directory = await getApplicationDocumentsDirectory();
      newPath = '${directory.path}${path ?? ''}';
    }
    final dir = Directory(newPath);
    if (!dir.existsSync()) {
      await dir.create(recursive: true);
    }
    return newPath;
  }

  /// 保存图片
  static Future<File?> saveImage({
    Uint8List? imageData,
    String? url,
  }) async {
    if (imageData != null) {
      return saveImageData(imageData: imageData);
    }
    return saveNetworkImage(url);
  }

  /// 下载并保存网络图片
  static Future<File?> saveNetworkImage(String? url) async {
    if (url == null) {
      return null;
    }
    var httpClient = HttpClient();
    var request = await httpClient.getUrl(Uri.parse(url));
    var response = await request.close();
    var result = await consolidateHttpClientResponseBytes(response);
    // 保存路径
    final selectedDirectory =
        await FileManager.getHomeDirectoryPath(path: '/images');
    var name = url.split('/').last.split('.').first;
    final path = '$selectedDirectory/$name.png';
    File imageFile = File(path);
    if (imageFile.existsSync()) {
      return imageFile;
    }
    // 写入文件
    final newFile = await imageFile.writeAsBytes(result);
    return newFile;
  }

  /// 保存图片到本地
  static Future<File?> saveImageData({
    String? name,
    Uint8List? imageData,
  }) async {
    if (imageData == null) {
      return null;
    }
    final directory = await getApplicationDocumentsDirectory();
    final path =
        '${directory.path}/${name ?? DateTime.now().millisecondsSinceEpoch.toString()}.png';
    final file = await File(path).create();
    await file.writeAsBytes(imageData);
    return file;
  }

  /// 保存图片到相册
  static Future<bool> saveImageToGallery({
    Uint8List? imageData,
    File? image,
    String? localPath, // 本地路径
    String? bundlePath, // bundle路径
    String? urlString,
  }) async {
    Uint8List? imageBytes = imageData;
    if (image != null) {
      imageBytes = image.readAsBytesSync();
    }
    if (localPath != null && localPath != '') {
      imageBytes = File(localPath).readAsBytesSync();
    }
    if (bundlePath != null && bundlePath != '') {
      final value = await rootBundle.load(bundlePath);
      imageBytes = value.buffer.asUint8List();
    }
    if (urlString != null && urlString != '') {
      var httpClient = HttpClient();
      var request = await httpClient.getUrl(Uri.parse(urlString));
      var response = await request.close();
      imageBytes = await consolidateHttpClientResponseBytes(response);
    }
    if (imageBytes != null) {
      final result = await ImageGallerySaver.saveImage(imageBytes);
      if (result['isSuccess'] == true) {
        return true;
      }
    }
    return false;
  }

  /// 保存(视频)文件到相册
  static Future<bool> saveFileToGallery({String? filePath}) async {
    if (filePath != null) {
      final result = await ImageGallerySaver.saveFile(filePath);
      if (result['isSuccess'] == true) {
        Toast.show(PublicText.saveSuccess);
        return true;
      }
    }
    return Future.value(false);
  }
}
